package kai.rating;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper
{
	private static final String DB_NAME="kai_rating.db";
	private static final String TABLE_OBJ="object";
	private static final int DB_VERSION=1;
	private static final int point=1400;
	//static Context con;
	protected DBHelper(Context c)
	{
		super(c,DB_NAME,null,DB_VERSION);
		//con=c;
	}
	@Override
	public void onCreate(SQLiteDatabase db)
	{
		db.execSQL("CREATE TABLE object(name text not null unique,point integer not null default "+point+");");

		//for Test
		MakeObjs(db,"Kjwon15");
		MakeObjs(db,"Kai Systems");
	}
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	{
		db.execSQL("drop table "+TABLE_OBJ);
		onCreate(db);
	}

	protected static int GetRows(SQLiteDatabase db)
	{
		Cursor result=null;
		try{
			result=db.query(TABLE_OBJ,new String[] {"rowid"},null,null,null,null,null);
			
		}catch(SQLException se)
		{
			result.close();
			return -1;
		}
		int ret=result.getCount();
		result.close();
		return ret;
	}

	protected static void GetObjs(SQLiteDatabase db,EloObject[] objs,String order)
	{
		Cursor result = null;
		int numrow = 0;
		result=db.query(TABLE_OBJ, new String[] {"rowid","name","point"},null,null,null,null,order);
		numrow=result.getCount();
		result.moveToFirst();
		
		for(int i=0;i<numrow;i++)
		{
			objs[i].id=result.getInt(0);
			objs[i].name=result.getString(1);
			objs[i].point=result.getInt(2);
			result.moveToNext();
		}
		result.close();
	}
	
	protected static int MakeObjs(SQLiteDatabase db,String name)
	{
		if(name.length()==0)
			return -1;
		Cursor result;
		result=db.query(TABLE_OBJ, new String[] {"rowid"},"name=\""+name+"\"",null,null,null,null);
		if(result.getCount()>0)
		{
			result.close();
			return -1;
		}
		result.close();
		ContentValues values=new ContentValues();
		values.put("name",name);
		return (int)db.insert(TABLE_OBJ, null, values);
	}
	protected static void DeleteObjs(SQLiteDatabase db,int rowid)
	{
		db.delete(TABLE_OBJ,"rowid="+rowid,null);
	}
	
	protected static boolean SetPoint(SQLiteDatabase db,int id,int point)
	{
		ContentValues values=new ContentValues();
		values.put("point", point);
		try{
			db.update(TABLE_OBJ,values,"rowid="+Integer.toString(id),null);
		}catch(SQLException se)
		{
			return false;
		}
		return true;
	}
	
}